import 'dart:math';

import 'package:dailoz/constants.dart';
import 'package:dailoz/data/loading_data.dart';
import 'package:dailoz/generated/l10n.dart';
import 'package:dailoz/service/user_service/user_service.dart';
import 'package:dailoz/size_config.dart';
import 'package:dailoz/utils/custom_vertification_code.dart';
import 'package:dailoz/utils/toast.dart';
import 'package:dailoz/utils/validate.dart';
import 'package:dailoz/view_model/user.dart';
import 'package:dailoz/views/home.dart';
import 'package:dailoz/views/sign_up.dart';
import 'package:dailoz/widgets/bottom_login_signup_text_button.dart';
import 'package:dailoz/widgets/button_widget.dart';
import 'package:dailoz/widgets/input_field.dart';
import 'package:dailoz/widgets/progress_widget.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class Login extends StatefulWidget {
  const Login({Key? key}) : super(key: key);

  static String id = 'login_view';

  @override
  State<Login> createState() => _LoginState();
}

class _LoginState extends State<Login> {
  late String code;

  bool isLoading = false;
  bool passwordInvisible = true;

  IconData? passwordVisibleIcon = Icons.visibility_off_outlined;

  TextEditingController? _userPhoneController;
  TextEditingController? _passwordController;
  TextEditingController? _validateCodeController;

  FocusNode? _userPhoneNode;
  FocusNode? _passwordNode;
  FocusNode? _validateCodeNode;

  _login(BuildContext context, WebSocketData? provider, String? userName,
      String? password, String? validateCode) async {
    setState(() {
      isLoading = !isLoading;
    });
    // 判断是否为空
    if (userName == "") {
      showToast(S.of(context).phoneNotNull);
      _userPhoneNode?.requestFocus();
      setState(() {
        isLoading = !isLoading;
      });
      return;
    } else if (!Validate.validatePhoneNumber(_userPhoneController!.text)) {
      showToast(S.of(context).validatePhoneNum);
      _userPhoneNode?.requestFocus();
      _userPhoneController?.clear();
      _passwordController?.clear();
      _validateCodeController?.clear();
      _getCode();
      setState(() {
        isLoading = !isLoading;
      });
      return;
    } else if (password == "") {
      showToast(S.of(context).passwordNotNull);
      _passwordNode?.requestFocus();
      setState(() {
        isLoading = !isLoading;
      });
      return;
    } else if (validateCode == "") {
      showToast(S.of(context).codeNotNull);
      _validateCodeNode?.requestFocus();
      setState(() {
        isLoading = !isLoading;
      });
      return;
    } else if (validateCode?.toLowerCase() != code.toLowerCase()) {
      showToast(S.of(context).validateCodeError);
      _validateCodeController?.clear();
      _validateCodeNode?.requestFocus();
      _getCode();
      setState(() {
        isLoading = !isLoading;
      });
      return;
    } else {
      // User userInfo = User(
      //     phoneNum: int.parse(_userPhoneController!.text), password: password);
      // dynamic response = await UserService.login(userInfo);
      // if (response != null) {
      //   if (!mounted) return;
      //   UserService.loginOperation(context, response, provider!);
      // }
      User user = User(
          phoneNum: int.parse(_userPhoneController!.text), password: password);
      bool flag = await UserService.login(user);
      if (flag) {
        if (!mounted) return;
        Navigator.of(context)
            .pushNamedAndRemoveUntil(Home.id, (Route<dynamic> route) => false);
      }
    }
    setState(() {
      isLoading = !isLoading;
    });
  }

  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
    print("change");
  }

  @override
  void initState() {
    super.initState();
    _getCode();
    _userPhoneController = TextEditingController();
    _passwordController = TextEditingController();
    _validateCodeController = TextEditingController();
    _userPhoneNode = FocusNode();
    _passwordNode = FocusNode();
    _validateCodeNode = FocusNode();
  }

  @override
  void dispose() {
    super.dispose();
    _userPhoneController?.dispose();
    _passwordController?.dispose();
    _validateCodeController?.dispose();
    _validateCodeNode?.dispose();
    _userPhoneNode?.dispose();
    _passwordNode?.dispose();
  }

  // 调用随机数方法
  _getCode() {
    code = '';
    String? alphabet = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM';
    for (int i = 0; i < 4; i++) {
      String charOrNum = Random().nextInt(2) % 2 == 0 ? "char" : "num";
      switch (charOrNum) {
        case "char":
          code += alphabet[Random().nextInt(alphabet.length)];
          break;
        case "num":
          code += Random().nextInt(9).toString();
          break;
      }
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    final provider = Provider.of<WebSocketData>(context);
    return ProgressWidget(
      loading: isLoading,
      msg: S.of(context).isLogin,
      child: GestureDetector(
        onTap: () {
          _userPhoneNode!.unfocus();
          _passwordNode!.unfocus();
          _validateCodeNode!.unfocus();
        },
        child: Scaffold(
          resizeToAvoidBottomInset: false,
          body: Center(
            child: SizedBox(
              width: SizeConfig.getProportionateScreenWidth(315.0),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  SizedBox(
                    height: SizeConfig.getProportionateScreenHeight(50.0),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      Text(
                        S.of(context).loginButtonText,
                        style: Theme.of(context).textTheme.bodyText1?.copyWith(
                              fontSize:
                                  SizeConfig.getProportionateFontSize(36.0),
                            ),
                      ),
                    ],
                  ),
                  SizedBox(
                    height: SizeConfig.getProportionateScreenHeight(60.0),
                  ),
                  InputField(
                    focusNode: _userPhoneNode,
                    controller: _userPhoneController,
                    keyboardType: TextInputType.text,
                    borderColor: inputBorderColor,
                    borderWidth: 1.0,
                    hintText: S.of(context).phoneNum,
                    prefixIcon: Icons.phone_outlined,
                    prefixIconColor: inputIconColor,
                    prefixIconSize: SizeConfig.getProportionateFontSize(22.0),
                    hintTextColor: inputHintTextColor,
                    hintTextSize: 16.0,
                  ),
                  SizedBox(
                    height: SizeConfig.getProportionateScreenHeight(12.0),
                  ),
                  InputField(
                    focusNode: _passwordNode,
                    controller: _passwordController,
                    keyboardType: TextInputType.text,
                    borderColor: inputBorderColor,
                    borderWidth: 1.0,
                    hintText: S.of(context).password,
                    textInvisible: passwordInvisible,
                    hintTextColor: inputHintTextColor,
                    prefixIcon: Icons.lock_outline,
                    prefixIconColor: inputIconColor,
                    prefixIconSize: SizeConfig.getProportionateFontSize(22.0),
                    suffixIcon: passwordVisibleIcon,
                    suffixOnPress: () {
                      setState(() {
                        passwordInvisible = !passwordInvisible;
                        if (passwordVisibleIcon ==
                            Icons.visibility_off_outlined) {
                          passwordVisibleIcon = Icons.visibility_outlined;
                        } else {
                          passwordVisibleIcon = Icons.visibility_off_outlined;
                        }
                      });
                    },
                    suffixIconColor: inputIconColor,
                    suffixIconSize: SizeConfig.getProportionateFontSize(16.0),
                    hintTextSize: 16.0,
                  ),
                  SizedBox(
                    height: SizeConfig.getProportionateScreenHeight(15.0),
                  ),
                  Row(
                    children: [
                      SizedBox(
                        width: SizeConfig.getProportionateScreenWidth(180.0),
                        child: Padding(
                          padding: const EdgeInsets.only(right: 18.0),
                          child: InputField(
                            keyboardType: TextInputType.text,
                            focusNode: _validateCodeNode,
                            controller: _validateCodeController,
                            borderColor: inputBorderColor,
                            borderWidth: 1.0,
                            hintTextSize: 16.0,
                            prefixIcon: Icons.key,
                            prefixIconColor: inputIconColor,
                            prefixIconSize:
                                SizeConfig.getProportionateFontSize(22.0),
                            hintText: S.of(context).validateCode,
                            hintTextColor: inputHintTextColor,
                          ),
                        ),
                      ),
                      InkWell(
                        child: Container(
                          padding: const EdgeInsets.only(left: 10),
                          decoration: const BoxDecoration(
                            color: Colors.white,
                            border: Border(
                              left: BorderSide(
                                width: 1,
                                color: Color(0xffc7c7c7),
                              ),
                            ),
                          ),
                          child: CustomVerificationCode(
                            code: code,
                          ),
                        ),
                        onTap: () {
                          _getCode();
                        },
                      )
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      TextButton(
                        onPressed: () {},
                        child: Text(
                          S.of(context).forgetPassword,
                          style: TextStyle(
                            color: buttonWidgetColor,
                            fontSize: SizeConfig.getProportionateFontSize(12.0),
                          ),
                        ),
                      ),
                    ],
                  ),
                  SizedBox(
                    height: SizeConfig.getProportionateScreenHeight(40.0),
                  ),
                  ButtonWidget(
                    width: 320.0,
                    height: 52.0,
                    buttonText: S.of(context).loginButtonText,
                    onPressed: () {
                      _login(
                        context,
                        provider,
                        _userPhoneController?.text,
                        _passwordController?.text,
                        _validateCodeController?.text,
                      );
                    },
                    buttonColor: buttonWidgetColor,
                    buttonTextColor: Colors.white,
                  ),
                  SizedBox(
                    height: SizeConfig.getProportionateScreenHeight(54.0),
                  ),
                  // const LoginSignUpDivider(),
                  // SizedBox(
                  //   height: SizeConfig.getProportionateScreenHeight(31.0),
                  // ),
                  // Row(
                  //   mainAxisAlignment: MainAxisAlignment.center,
                  //   children: <Widget>[
                  //     ThirdPartyLoginButton(
                  //       onPressed: () {},
                  //       icon: Icons.facebook,
                  //       iconColor: buttonWidgetColor,
                  //     ),
                  //     SizedBox(
                  //       width: SizeConfig.getProportionateScreenWidth(16.0),
                  //     ),
                  //     ThirdPartyLoginButton(
                  //       onPressed: () {
                  //         // test();
                  //       },
                  //       icon: Icons.wechat,
                  //       iconColor: Colors.green,
                  //     ),
                  //   ],
                  // ),
                  SizedBox(
                    height: SizeConfig.getProportionateScreenHeight(16.0),
                  ),
                  BottomLoginSignUpTextButton(
                    text: S.of(context).NoAccountText,
                    buttonText: S.of(context).signUpButtonText,
                    onPressed: () {
                      Navigator.pushReplacementNamed(context, SignUp.id);
                    },
                  )
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
